// pages/user/myShop/myShop.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    titleArr: [{ 'tit': '请选择：' },{ 'tit': '企业名称：' }, { 'tit': '姓名：' }, { 'tit': '电话：' }, { 'tit': '职位：' }, { 'tit': '地址：' }],
    //productArr: [{ 'tit': '测试一' }, { 'tit': '测试二' }, { 'tit': '测试三' }, { 'tit': '测试四' }, { 'tit': '测试五' }],
    productArr: [{ 'goods_id': '', 'img': '' }, { 'goods_id': '', 'img': '' }],
    isAgree: false,//是否同意规则
    postData: {},//请求数据
    shopImg: [],
    licenseImg: [],
    pickList: ['采购','供货'],
    customerRadio:[{value:"0",checked:true},{value:"1",checked:false}],
    pickIndex:'0',
  },

  //规则点击
  rulesClick: function () {
    console.log('规则点击');
    wx.navigateTo({
      url: '../../rules/rules',
    })
  },
  radioChange:function(e){
    var that = this;
    that.setData({
      pickIndex:e.detail.value
    })
  },
  //上传营业执照
  chooseLicenec: function () {
    var that = this;
    wx.chooseImage({
      success: function (res) {
        console.log(res.tempFilePaths);
        var nlicenseImg = new Array();
        nlicenseImg[0] = res.tempFilePaths[0];
        that.setData({
          licenseImg: nlicenseImg,
        })
        wx.showLoading({
          title: '正在上传图片',
        })
        that.uploadimg({
          url: app.globalData.requestURL + 'file/uploadImg',
          path: that.data.licenseImg,
          oldName: that.data.postData.license ? that.data.postData.license : '',
          tit: 'license',
        })
      },
    })
  },

  /*
      wx.chooseLocation({
      success: function(res) {
        console.log(res.name);
        console.log(res.address);
        data['shop_addr'] = res.address;
        data['longitude'] = res.longitude;
        data['latitude'] = res.latitude;
        that.setData({
            postData: data,
        })
      },
    })
  */
  picker: function (e) {
    this.setData({
      pickIndex: e.detail.value
    })
  },
  //选择地址
  chooseAddress: function () {
    var that = this;
    var data = that.data.postData;
    wx.chooseLocation({
      success: function (res) {
        console.log(res.name);
        console.log(res.address);
        data['address'] = res.address;
        data['longitude'] = res.longitude;
        data['latitude'] = res.latitude;
        that.setData({
          postData: data,
        })
      },
    })
  },

  //是否同意规则
  rulesAgree: function () {
    var that = this;
    that.setData({
      isAgree: !that.data.isAgree,
    })

  },
  //输入信息
  messageInput: function (e) {

    var that = this;
    var data = that.data.postData;
    if(e.currentTarget.id == 0){
      console.log('企业名称');
      data['customerType'] = e.detail.value;
    }else if (e.currentTarget.id == 1) {
      console.log('企业名称');
      data['ename'] = e.detail.value;
    } else if (e.currentTarget.id == 2) {
      console.log('姓名');
      data['cname'] = e.detail.value;
    } else if (e.currentTarget.id == 3){
      console.log('电话');
      data['tel'] = e.detail.value;
    } else if (e.currentTarget.id == "address"){
      console.log('地址');
      data['address'] = e.detail.value;
    } else {
      console.log('职位');
      data['postion'] = e.detail.value;
    }
    that.setData({
      postData: data,
    })
  },

  //发布按钮点击
  pushClick: function () {
    var that = this;
    if (that.data.isAgree) {
      if(!that.data.pickIndex){
        wx.showToast({
          title: '请选择您是需要采购还是供货',
          icon: 'none'
        })
      }else{
        if (!that.data.postData.ename || that.data.postData.ename.length == 0 || !that.data.postData.cname || that.data.postData.cname.length == 0 || !that.data.postData.tel||that.data.postData.tel.length == 0) {
          wx.showToast({
            title: '企业名称、姓名、电话不能为空',
            icon: 'none'
          })
        } 
        // else if (that.data.pickIndex == 0 && ( !that.data.postData.cname || that.data.postData.cname.length == 0 || !that.data.postData.tel || that.data.postData.tel.length == 0)){
        //   wx.showToast({
        //     title: '姓名、电话不能为空',
        //     icon: 'none'
        //   })
        // } 
        else {
          that.requestData();//上传数据
        }
      }
      
    } else {
      wx.showToast({
        title: '请先阅读并同意相关条款',
        icon: 'none'
      })
    }
  },

  //多张图片上传
  uploadimg: function (data) {
    console.log('------------');
    console.log(data.path);
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      header: {
        compress: '0',
        height: '108',
        width: '100',
        imgName: data.oldName,
      },
      name: 'fileData',
      formData: null,
      success: (resp) => {
        success++;
        console.log(resp.data)
        console.log(i);
        var result = JSON.parse(resp.data);
        if (result.code == 0) {
          var ndata = that.data.postData;
          if (data.tit == 'shop_img') {
            ndata['shop_img'] = result.resultData;
          } else {
            ndata['license'] = result.resultData;
          }
          that.setData({
            postData: ndata,
          })
        }
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        console.log(i);
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用   
          console.log('执行完毕');
          wx.hideLoading();
          console.log('成功：' + success + " 失败：" + fail);
        } else {//若图片还没有传完，则继续调用函数
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },

  //请求数据
  requestData: function () {
    var that = this;
    var data = that.data.postData;
    data['openId'] = wx.getStorageSync('userInfo').userId;
    that.setData({
      postData: data,
    })
    data['customerType'] = that.data.pickIndex;//卖家
    data['status'] = '1';//默认审核通过
    
    app.post('customer/saveOrUpdateCustomer', that.data.postData).then((res) => {
      console.log('success');
      console.log(res);
      if (res.code == 0) {
        var userInfo = wx.getStorageSync('userInfo');
        userInfo['isShopMsg'] = 0;
        wx.setStorageSync('userInfo', userInfo);
        wx.showModal({
          title: '温馨提示',
          content: '提交信息成功',
          showCancel: false, success(res) {
            wx.navigateBack();//返回上一页
          }
        })
       
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false,
        })
      }
    }).catch((errMsg) => {
      console.log('fail');
      console.log(errMsg + '失败');
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var pdata = that.data.postData;
    var pickIndex = that.data.pickIndex;
    pdata['userIcon'] = wx.getStorageSync('userInfo').user_icon;
    console.log(wx.getStorageSync('userInfo'));
    // 判断是否有店铺 有店铺请求店铺信息
    if (wx.getStorageSync('userInfo').isCustomer == 0) {
      app.post('customer/queryCustomer', { openId: wx.getStorageSync('userInfo').userId }).then((res) => {
        console.log('success');
        console.log(res);
        if (res.code == 0) {
          pdata['ename'] = res.resultData.customer.ename;
          pdata['cname'] = res.resultData.customer.cname;
          pdata['tel'] = res.resultData.customer.tel;
          pdata['postion'] = res.resultData.customer.postion;
          pdata['latitude'] = res.resultData.customer.latitude;
          pdata['longitude'] = res.resultData.customer.longitude;
          pdata['status'] = res.resultData.customer.status;
          pdata['address'] = res.resultData.customer.address;
          pdata['license'] = res.resultData.customer.license;
          pickIndex = res.resultData.customer.customer_type;
          if(pickIndex=="1"){
            that.setData({
              customerRadio: [{ value: "0", checked: false }, { value: "1", checked: true }],
            })
          }
          var nlicenseImg = new Array();
          nlicenseImg[0] = app.globalData.requestURL + 'upload/' + res.resultData.customer.license;
          //需要显示的图片的地址
          // var nshopImg = new Array();
          // var nlicenseImg = new Array();
          // nshopImg[0] = app.globalData.requestURL + 'upload/' + res.resultData.shopInfo.shop_img;
          // nlicenseImg[0] = app.globalData.requestURL + 'upload/' + res.resultData.shopInfo.license;

          // var nproductArr = new Array();
          // for (var i = 0; i < res.resultData.produces.length; i++) {
          //   console.log(res.resultData.produces[i].id)
          //   console.log(res.resultData.produces[i].pro_img.split(",")[0])
          //   var part = {};
          //   part.goods_id = res.resultData.produces[i].id;
          //   part.img = app.globalData.requestURL + 'upload/' + res.resultData.produces[i].pro_img.split(",")[0];
          //   nproductArr.push(part);
          // }

          that.setData({
            postData: pdata,
            pickIndex: pickIndex,
            // productArr: nproductArr,
            // shopImg: nshopImg,
            licenseImg: nlicenseImg,
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: res.msg,
            showCancel: false,
          })
        }
      }).catch((errMsg) => {
        console.log('fail');
        console.log(errMsg + '失败');
      })
    }
    that.setData({
      postData: pdata,
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})